import { create } from 'zustand';

export interface Message {
    id: string;
    type: 'user' | 'ai';
    content: string;
    timestamp: number;
    isStreaming?: boolean;
}

export interface ConversationGroup {
    id: string;
    userMessage: Message;
    aiMessage?: Message;
    timestamp: number;
    isComplete: boolean;
}
// startUserMessage(content)	创建新的用户消息，开始新对话组	用户开始说话时
// startAIResponse()	        为当前对话添加AI回复消息	AI开始回答时
// updateAIResponse(content, isComplete)	更新AI回复内容（流式）	AI回答过程中实时更新
// completeConversation()	    标记对话完成，移入历史记录	AI回答结束后，用户打断时
// limitConversations(maxCount)	限制历史对话数量	对话完成后清理
// clearConversations()	        清空所有对话	重置时使用

interface CaptionsState {
    conversations: ConversationGroup[];
    currentConversation: ConversationGroup | null;
    isUserSpeaking: boolean;

    // Actions 
    startUserMessage: (content: string) => void;
    completeUserMessage: () => void;
    startAIResponse: () => void;
    updateAIResponse: (content: string, isComplete?: boolean) => void;
    completeConversation: () => void;
    clearConversations: () => void;
    limitConversations: (maxCount?: number) => void;
}

const useCaptionsStore = create<CaptionsState>((set, get) => ({
    conversations: [],
    currentConversation: null,
    isUserSpeaking: false,

    startUserMessage: (content: string) => {
        const conversationId = `conv_${Date.now()}`;
        const userMessage: Message = {
            id: `user_${Date.now()}`,
            type: 'user',
            content,
            timestamp: Date.now(),
        };

        const newConversation: ConversationGroup = {
            id: conversationId,
            userMessage,
            timestamp: Date.now(),
            isComplete: false,
        };

        set({
            currentConversation: newConversation,
            isUserSpeaking: false,
        });
    },

    completeUserMessage: () => {
        set({ isUserSpeaking: false });
    },

    startAIResponse: () => {
        const { currentConversation } = get();
        if (!currentConversation) return;

        const aiMessage: Message = {
            id: `ai_${Date.now()}`,
            type: 'ai',
            content: '',
            timestamp: Date.now(),
            isStreaming: true,
        };

        set({
            currentConversation: {
                ...currentConversation,
                aiMessage,
            },
        });
    },

    updateAIResponse: (content: string, isComplete = false) => {
        const { currentConversation } = get();
        if (!currentConversation || !currentConversation.aiMessage) return;

        const updatedAIMessage: Message = {
            ...currentConversation.aiMessage,
            content,
            isStreaming: !isComplete,
        };

        set({
            currentConversation: {
                ...currentConversation,
                aiMessage: updatedAIMessage,
                isComplete,
            },
        });
    },

    completeConversation: () => {
        const { currentConversation, conversations } = get();
        if (!currentConversation) return;

        const completedConversation: ConversationGroup = {
            ...currentConversation,
            isComplete: true,
        };

        if (completedConversation.aiMessage) {
            completedConversation.aiMessage.isStreaming = false;
        }
        console.log('=========结束===========')
        set({
            conversations: [...conversations, completedConversation],
            currentConversation: null,
        });
    },

    clearConversations: () => {
        set({
            conversations: [],
            currentConversation: null,
            isUserSpeaking: false,
        });
    },

    // 限制对话历史数量，避免性能问题
    limitConversations: (maxCount: number = 10) => {
        const { conversations } = get();
        if (conversations.length > maxCount) {
            set({
                conversations: conversations.slice(-maxCount),
            });
        }
    },
}));

export default useCaptionsStore; 